package com.ledou44.ledousrad.service;

import com.ledou44.ledousrad.LedouSradBeanFactory;
import com.ledou44.ledousrad.dto.ServiceDTO;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * @author ledou44
 * 处理服务注册相关业务
 */
public class RegisterService {

    /**
     * 注册服务
     * @param serviceList 服务列表
     * @param key 维持连接的通道的hashcode
     * @param address 服务地址
     */
    public static void registerService(List<ServiceDTO> serviceList, String key, String address) {
        for(ServiceDTO service : serviceList) {
            service.setAddress(address);
            String name = service.getName();
            List<ServiceDTO> serviceDTOS = LedouSradBeanFactory.serviceBean.get(name);
            if(serviceDTOS == null) {
                List<ServiceDTO> putList = new ArrayList<>();
                putList.add(service);
                LedouSradBeanFactory.serviceBean.put(name, putList);
            } else {
                serviceDTOS.add(service);
            }
        }
        LedouSradBeanFactory.addressLinkService.put(key, serviceList);
    }

    /**
     * 移除服务
     * @param key 维持连接的通道的hashcode
     */
    public static void deleteRegisterService(String key) {
        List<ServiceDTO> serviceList = LedouSradBeanFactory.addressLinkService.get(key);
        if(CollectionUtils.isEmpty(serviceList)) {
            return;
        }
        for(ServiceDTO service : serviceList) {
            String name = service.getName();
            List<ServiceDTO> registerServiceList = LedouSradBeanFactory.serviceBean.get(name);
            if(CollectionUtils.isEmpty(registerServiceList)) {
                continue;
            }
            registerServiceList.remove(service);
            if(CollectionUtils.isEmpty(registerServiceList)) {
                LedouSradBeanFactory.serviceBean.remove(name);
            }
        }
        LedouSradBeanFactory.addressLinkService.remove(key);
    }

}
